package br.com.hermes.android.task;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import br.com.hermes.android.bt.DroidClient;
import br.com.hermes.bt.HmBluetoothDevice;
import br.com.hermes.bt.HmClient;
import br.com.hermes.bt.HmException;
import br.com.hermes.bt.HmStream;

public class DroidClientTask extends AsyncTask<HmBluetoothDevice, Void, HmStream>{

	private Handler handler;
	private Message message;
	
	private Activity activity;
	private ProgressDialog progressDialog;
	
	private HmClient bluetoothClient;
	
	public DroidClientTask(Activity activity, Handler handler, int what){
		this.activity = activity;
		this.handler  = handler;
		
		message       = new Message();
		message.what  = what;
		
		bluetoothClient = new DroidClient();
	}
	
	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		progressDialog = ProgressDialog.show(activity, "Aguarde", "Conectando com o dispositivo selecionado...");
	}
	
	@Override
	protected HmStream doInBackground(HmBluetoothDevice... devices) {
		
		HmStream stream = null;
		try {

			if(bluetoothClient.connect(devices[0])){
				
				stream = bluetoothClient.getHmStream();
			}
		} catch (HmException e) {

		}
		
		return stream;
	}
	
	@Override
	protected void onPostExecute(HmStream result) {
		super.onPostExecute(result);
		
		closeDialog();
		
		message.obj = result;
		handler.dispatchMessage(message);
	}
	
	private void closeDialog() {
		if (progressDialog != null && progressDialog.isShowing()) {
			progressDialog.dismiss();
		}
	}

}	